/*
 * Description: 菜单状态中心
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Dongxu.Ni
 * Date: 2020/3/10 18:00
 */
import { menuList, menuListFullBySession } from '../../api/sys/menu'
import { getLangMappingProperty } from '../../lang/lang-set'
import { ROOT_MENU_ID } from '../../const/server-map'
import { PATH_SEPARATOR } from '../../const/route-path'
import { SUPER_POST_ID } from '../../const/server-map'
import { privateRoutes } from '../../router'

// 第一次的时候，无数据
export function routesFormatToMenus(routes, parentRoutePath) {
  let retMenus = []
  for (const route of routes) {
    const routeChildren = route.children
    // 完整路由路径 这里使用PATH_SEPARATOR代表'/'根路径，否则当HOME_PATH不是'/'时候将会出错
    let completePath = parentRoutePath + PATH_SEPARATOR + route.path
    completePath = completePath.replace('//', '/')
    const menu = {
      menuId: completePath,
      menuNameZhCn: completePath,
      menuNameZhTw: completePath,
      menuNameEn: completePath,
      isCatalog: false,
      isForbidden: false,
      isOpen: false,
      order: 0,
      parentMenu: ROOT_MENU_ID,
      buttons: []
    }
    retMenus.push(menu)
    if (routeChildren && routeChildren.length > 0) {
      retMenus = retMenus.concat(routesFormatToMenus(routeChildren, completePath))
    }
  }
  return retMenus
}

// 菜单集合转菜单树
export function menuListToMenuTree(menuList, parentMenuId) {
  if (!parentMenuId) {
    parentMenuId = ROOT_MENU_ID
  }
  const retMenuTree = []
  // 首先遍历当前父级菜单的子集
  for (let i = 0, lenI = menuList.length; i < lenI; i++) {
    const tempI = menuList[i]
    const menuFuncList = tempI.menuFuncList
    if (menuFuncList && menuFuncList.length > 0) {
      for (const menuFunc of menuFuncList) {
        menuFunc.checked = false
      }
    }
    if (tempI.parentMenu === parentMenuId) {
      retMenuTree.push(tempI)
    }
  }
  // 然后遍历子集菜单，如果类型是目录的继续获取菜单子集
  for (let j = 0, lenJ = retMenuTree.length; j < lenJ; j++) {
    const temp = retMenuTree[j]
    if (temp.isCatalog) {
      temp.children = menuListToMenuTree(menuList, temp.menuId)
    }
  }
  return retMenuTree
}

const state = {
  // customMenuCollects
  customMenuCollects: [
    {
      menuId: '/Login',
      menuNameEn: 'user login',
      menuNameZhCn: '用户登录',
      menuNameZhTw: '用户登錄'
    },
    {
      menuId: '/Logout',
      menuNameEn: 'user logout',
      menuNameZhCn: '用户登出',
      menuNameZhTw: '用户登出'
    }
  ],
  //  全局菜单集合数据
  menuCollects: [],
  // 当前会话的岗位菜单集合（之所以不用tree是因为变化lang的时候递归变化太麻烦）
  sessionPostMenuList: [],
  // 当前会话激活的菜单
  sessionActiveMenu: ''
}

const getters = {
  getMenuNameById: state => menuId => {
    const menu = state.menuCollects.find(menu => menu.menuId === menuId)
    return menu ? menu.menuName : menuId
  },
  getMenuCollects: state => state.menuCollects,
  getSessionPostMenuTree: state => menuListToMenuTree(state.sessionPostMenuList),
  getSessionActiveMenu: state => state.sessionActiveMenu,
  // getSessionActiveMenuParentName: state => {
  //   const menu = state.menuCollects.find(menu => menu.menuId === state.sessionActiveMenu)

  //   return menu ? menu.parentMenu.replace(new RegExp('#'), '') : state.sessionActiveMenu
  // },
  getSessionActiveMenuName: state => {
    const menu = state.menuCollects.find(menu => menu.menuId === state.sessionActiveMenu)
    return menu ? menu.menuName : state.sessionActiveMenu
  },
  getSessionPostMenuList: state => {
    return state.sessionPostMenuList.filter(menu => !menu.isCatalog)
  }
}

const mutations = {
  SET_MENU_COLLECTS: (state, menuCollects) => {
    state.menuCollects = menuCollects
  },
  SET_SESSION_POST_MENU_LIST: (state, sessionPostMenuList) => {
    state.sessionPostMenuList = sessionPostMenuList
  },
  SET_SESSION_ACTIVE_MENU: (state, sessionActiveMenu) => {
    state.sessionActiveMenu = sessionActiveMenu
  },
  SET_MENU_WITH_LANGUAGE: (state, language) => {
    const langMappingProperty = getLangMappingProperty(language, 'menuName')
    for (const menu of state.menuCollects) {
      menu.menuName = menu[langMappingProperty]
    }
    for (const menu of state.sessionPostMenuList) {
      menu.menuName = menu[langMappingProperty]
    }
  }
}

const actions = {
  initSessionPostMenuList({ commit, rootState }) {
    const language = rootState.language.language
    const activePost = rootState.post.sessionPost.postId
    const langMappingProperty = getLangMappingProperty(language, 'menuName')
    return new Promise((resolve, reject) => {
      // 获取当前会话当前岗位的菜单集合
      menuListFullBySession()
        .then(response => {
          let menuList = response.data
          if (menuList.length === 0 && activePost === SUPER_POST_ID) {
            menuList = routesFormatToMenus(privateRoutes, '')
          }
          // 排序
          menuList.sort((a, b) => {
            return a.order - b.order
          })
          for (const menu of menuList) {
            if (!menu.isCatalog && menu.menuFuncList == null) {
              menu.menuFuncList = []
            }
            menu.menuName = menu[langMappingProperty]
          }
          commit('SET_SESSION_POST_MENU_LIST', menuList)
          resolve()
        })
        .catch(err => reject(err))
    })
  },
  initMenuCollects({ commit, state, rootState }) {
    const language = rootState.language.language
    const langMappingProperty = getLangMappingProperty(language, 'menuName')
    return new Promise((resolve, reject) => {
      menuList({})
        .then(response => {
          const menuList = state.customMenuCollects.concat(response.data)
          for (const menu of menuList) {
            menu.menuName = menu[langMappingProperty]
          }
          commit('SET_MENU_COLLECTS', menuList)
          resolve()
        })
        .catch(err => reject(err))
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
